/*
 *  Copyright 2012 yura.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.odg.dg.logicbeans;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Collections;
import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.opu.odg.dg.xml.XmlCharsetUtils;

/**
 *
 * @author yura
 */
public class SingleFileTemplateForDG implements TemplateFile {
    static final String CONTENT = "content";

    private String content;
    private String encoding;

    @Override
    public void load(InputStream is) throws IOException {
        byte[] data = IOUtils.toByteArray(is);
        IOUtils.closeQuietly(is);

        Charset xmlEncoding = null;
        try {
            xmlEncoding = XmlCharsetUtils.getXmlEncoding(new String(data,
                    Charset.forName("UTF-8")));
        } catch (Exception e) {
        }

        if (xmlEncoding != null) {
            encoding = xmlEncoding.name();
            content = new String(data, encoding);
        } else {
            InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(data));
            encoding = isr.getEncoding();
            content = IOUtils.toString(isr);
        }

        if (!DEFAULT_ENCODING.equals(encoding)) {
            System.err.format("[%s]: The encoding is: %s", getClass().getName(), encoding);
        }
    }

    @Override
    public Map<String, String> getTemplateFileContent() {
        return Collections.singletonMap(CONTENT, content);
    }

    @Override
    public void setResolvedFileContent(Map<String, String> data) {
        content = data.get(CONTENT);
    }

    @Override
    public void store(OutputStream os) throws IOException {
        IOUtils.write(content, os, getEncoding());
        IOUtils.closeQuietly(os);
    }

    public String getEncoding() {
        return encoding != null ? encoding : DEFAULT_ENCODING;
    }

    public String getContent() {
        return content;
    }
}
